<?php


/**
 * 获取爆料分类
 */
if($uri == "/api/user/release/category"){
    $data = $cnSql->read_all("template_categories", "is_active = 1");
    $outJson->data = $data;
    $outJson->msg = "获取成功";
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}

/**
 * 获取爆料任务ID
 */
if($uri == "/api/user/release/get"){
    //根据token获取用户信息
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $userInfo = $cnSql->read_only("users", "token = '$token' and type = 0");
    if(!$userInfo){
        $outJson->msg = "用户不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 获取用户选择的模板类型
    $types = isset($_GET['types']) ? explode(',', $_GET['types']) : [];
    if(empty($types)){
        $outJson->msg = "请选择任务类型";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 检查是否有超时任务需要重置
    $cnSql->custom("UPDATE releases SET 
        status = 0,
        call_time = NULL,
        timeout = NULL, 
        user_id = NULL
    WHERE status = 1 
    AND timeout < NOW()");
    
    $user_id = $userInfo['id'];

    // 获取用户可做的模板
    $available_templates = [];
    foreach($types as $template_id) {
        // 获取该用户今日对该模板的完成次数
        $completed_count = $cnSql->custom("SELECT COUNT(*) as count FROM submit_details 
            WHERE template_id = $template_id 
            AND user_id = $user_id 
            AND DATE(create_time) = CURDATE()"
        )[0]['count'];

        // 获取模板信息和限制次数
        $template = $cnSql->read_only("templates", "id = $template_id");
        if($template) {
            $limit = intval($template['user_task_limit']);
            if($limit <= 0 || $completed_count < $limit) {
                $available_templates[] = $template_id;
            }
        }
    }

    if(empty($available_templates)){
        $outJson->msg = "所选任务类型已达到限制次数";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 获取可用任务
    $template_ids = implode(',', $available_templates);
    $data = $cnSql->read_only("releases", "status = 0 AND template_id IN ($template_ids)");
    
    if($data){
        $template = $cnSql->read_only("templates", "id = $data[template_id]");
        $timeout = $template['duration'] ? $template['duration'] : 3600;
        $cnSql->update_json("releases", array(
            "status" => 1,
            "user_id" => $user_id,
            "call_time" => date("Y-m-d H:i:s"),
            "timeout" => date("Y-m-d H:i:s",strtotime("+$timeout second"))
        ), "id = $data[id]");
        
        // 只返回任务ID
        $outJson->data = array(
            'task_id' => $data['id']
        );
        $outJson->msg = "获取成功";
        $outJson->code = 200;
    }else{
        $outJson->msg = "暂无可用任务";
        $outJson->code = 400;
    }
    echo json_encode($outJson);
    exit;
}

/**
 * 获取爆料任务详情
 */
if($uri == "/api/user/release/detail"){
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $userInfo = $cnSql->read_only("users", "token = '$token' and type = 0");
    if(!$userInfo){
        $outJson->msg = "用户不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    $task_id = isset($_GET['task_id']) ? intval($_GET['task_id']) : 0;
    if(!$task_id){
        $outJson->msg = "任务ID不能为空";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 获取任务信息并验证
    $task = $cnSql->read_only("releases", "id = $task_id");
    if(!$task){
        $outJson->msg = "任务不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 验证任务状态和所属用户
    if($task['status'] != 1){
        $outJson->msg = "任务状态异常";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    if($task['user_id'] != $userInfo['id']){
        $outJson->msg = "无权访问该任务";
        $outJson->code = 403;
        echo json_encode($outJson);
        exit;
    }

    // 检查任务是否超时
    if(strtotime($task['timeout']) < time()){
        $outJson->msg = "任务已超时";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 获取模板信息
    $template = $cnSql->read_only("templates", "id = $task[template_id]");
    if(!$template){
        $outJson->msg = "模板不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 返回任务和模板信息
    $outJson->data = array(
        'task' => $task,
        'template' => $template
    );
    $outJson->msg = "获取成功";
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}

/**
 * 上传爆料图片
 */
if($uri == "/api/user/release/upload"){
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $user = $cnSql->read_only("users", "token = '$token' and type = 0");
    if(!$user){
        $outJson->msg = "用户不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 检查是否有文件上传
    if(!isset($_FILES['file'])) {
        $outJson->msg = "未检测到上传文件";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    $file = $_FILES['file'];
    
    // 检查上传是否出错
    if($file['error'] !== 0) {
        $outJson->msg = "文件上传失败";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 检查文件类型
    $allowed = array('image/jpeg', 'image/png', 'image/gif');
    if(!in_array($file['type'], $allowed)) {
        $outJson->msg = "只允许上传JPG、PNG或GIF图片";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // try {
    //     // 创建Imagick对象
    //     $image = new Imagick($file['tmp_name']);
        
    //     // 获取原图尺寸
    //     $dimensions = $image->getImageGeometry();
    //     $width = $dimensions['width'];
    //     $height = $dimensions['height'];
        
    //     // 如果宽度超过1080，等比例缩放
    //     if($width > 1080) {
    //         $image->scaleImage(1080, 0); // 0表示自动计算高度保持比例
    //     }
        
    //     // 设置压缩质量
    //     $image->setImageCompression(Imagick::COMPRESSION_JPEG);
    //     $image->setImageCompressionQuality(90);
        
    //     // 转换为jpg格式
    //     $image->setImageFormat('jpg');
        
    //     // 创建临时文件
    //     $temp_file = tempnam(sys_get_temp_dir(), 'IMG');
    //     $image->writeImage($temp_file);
        
    //     // 清理资源
    //     $image->clear();
    //     $image->destroy();
        
    //     // 将临时文件赋值给$file
    //     $file['tmp_name'] = $temp_file;
    //     $file['type'] = 'image/jpeg';
    // } catch(Exception $e) {
    //     $outJson->msg = "图片处理失败: " . $e->getMessage();
    //     $outJson->code = 500;
    //     echo json_encode($outJson);
    //     exit;
    // }

    // 检查文件大小(最大10MB)
    if($file['size'] > 10 * 1024 * 1024) {
        $outJson->msg = "文件大小不能超过10MB";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 生成唯一文件名
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = date('YmdHis') . '_' . uniqid() . '.' . $ext;
    
    // 确保上传目录存在
    $upload_dir = 'uploads/release/';
    if(!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    // 移动文件到目标位置
    if(move_uploaded_file($file['tmp_name'], $upload_dir . $filename)) {
        $outJson->data = array(
            'url' => '/' . $upload_dir . $filename
        );
        $outJson->msg = "上传成功";
        $outJson->code = 200;
    } else {
        $outJson->msg = "文件保存失败";
        $outJson->code = 500;
    }
    
    echo json_encode($outJson);
    exit;
}

/**
 * 提交爆料任务
 */
if($uri == "/api/user/release/submit"){
    // 获取POST数据
    $post = json_decode(file_get_contents('php://input'), true);
    if(!$post) {
        $outJson->msg = "无效的请求数据";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $user = $cnSql->read_only("users", "token = '$token' and type = 0");
    if(!$user){
        $outJson->msg = "用户不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }
    
    // 验证必要字段
    if(empty($post['task_id']) || !isset($post['input_values']) || !isset($post['image_paths'])) {
        $outJson->msg = "缺少必要参数";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    $release = $cnSql->read_only("releases", "id = $post[task_id]");
    if(!$release){
        $outJson->msg = "任务不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }
    $template = $cnSql->read_only("templates", "id = $release[template_id]");
    if(!$template){
        $outJson->msg = "模板不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

 
    // 插入数据库
    $sql_id = $cnSql->insert_json("submit_details", array(
        'task_id' => $release['id'],
        'template_id' => $release['template_id'],
        'user_id' => $user['id'],
        'out_structure' => json_encode($post['input_values'], JSON_UNESCAPED_UNICODE),
        'image_paths' => json_encode($post['image_paths']),
        'create_time' => date('Y-m-d H:i:s')
    ));

    if($sql_id) {
        $cnSql->update_json("releases", array("status"=>2), "id = $release[id]");
        $outJson->msg = "提交成功";
        $outJson->code = 200;
    } else {
        $outJson->msg = "提交失败";
        $outJson->code = 500;
    }
    
    echo json_encode($outJson);
    exit;
}


/**
 * 获取模板列表
 */
if($uri == "/api/user/release/template"){
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $userInfo = $cnSql->read_only("users","token = '$token' and type = 0");
    if(!$userInfo){
        $outJson->msg = "用户不存在:$token";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }
    $category_id = isset($_GET['category_id']) ? intval($_GET['category_id']) : 0;
    $where = "is_open = 1";
    if($category_id > 0) {
        $where .= " AND category_id = $category_id";
    }
    $data = $cnSql->read_all("templates", $where);
    // 遍历每个模板,计算用户已完成次数和剩余可做次数
    foreach($data as &$template) {
        // 获取该用户今日对该模板的完成次数
        $template_id = $template['id'];
        $completed_count = $cnSql->custom("SELECT COUNT(*) as count FROM submit_details 
            WHERE template_id = $template_id 
            AND user_id = $userInfo[id] 
            AND DATE(create_time) = CURDATE()"
        )[0]['count'];

        // 计算剩余可做次数
        $limit = intval($template['user_task_limit']); 
        if($limit > 0) {
            $template['remaining_count'] = $limit - $completed_count;
            $template['is_limit_exceeded'] = $template['remaining_count'] <= 0;
        } else {
            // 无限制
            $template['remaining_count'] = -1;
            $template['is_limit_exceeded'] = false;
        }
        $template['completed_count'] = $completed_count;
    }
    $outJson->data = $data;
    $outJson->msg = "获取成功";
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}


/**
 * 获取爆料明细
 */
if($uri == "/api/user/release/list"){
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $userInfo = $cnSql->read_only("users", "token = '$token'");
    if(!$userInfo){
        $outJson->msg = "用户不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $page_size = isset($_GET['page_size']) ? intval($_GET['page_size']) : 20;
 
    $status = $_GET['status'] ? $_GET['status'] : 0;
    // 如果是进行中的任务,查询releases表
    if($status == 0) {
        $where = "status = 1 and user_id = $userInfo[id] order by call_time desc";
        $data = $cnSql->read("releases", $page, $page_size, $where, $total);
        $outJson->data = $data;
        $outJson->total = $total;
        $outJson->msg = "获取成功";
        $outJson->code = 200;
        echo json_encode($outJson);
        exit;
    }
    $where = "status = $status and user_id = $userInfo[id] order by create_time desc";
 
    $data = $cnSql->read("submit_details", $page, $page_size,$where,$total);
    $outJson->data = $data;
    $outJson->total = $total;
    $outJson->msg = "获取成功";
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}

/**
 * 统计进行中和待审核任务数量
 */
if($uri == "/api/user/release/task_count"){
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $userInfo = $cnSql->read_only("users", "token = '$token' and type = 0");
    if(!$userInfo){
        $outJson->msg = "用户不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 重置已超时的任务
    $cnSql->custom("UPDATE releases SET 
        status = 0,
        call_time = NULL,
        timeout = NULL,
        user_id = $userInfo[id] 
    WHERE status = 1 
    AND timeout < NOW()");

    // 统计进行中的任务数量(status=1)
    $ongoing = $cnSql->total("releases", "status = 1 and user_id = $userInfo[id]");

    // 统计待审核的任务数量(status=2)
    $pending = $cnSql->total("submit_details", "status = 1 and user_id = $userInfo[id]");

    $outJson->data = array(
        "ongoing" => intval($ongoing),
        "pending" => intval($pending)
    );
    $outJson->msg = "获取成功";
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}


/**
 * 统计明细
 */
if($uri == "/api/user/release/count"){
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $userInfo = $cnSql->read_only("users", "token = '$token' and type = 0");
    if(!$userInfo){
        $outJson->msg = "用户不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }
    // 统计今日数据
    $today_stats = $cnSql->custom("SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as success,
        SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as failed
    FROM submit_details 
    WHERE user_id = $userInfo[id] 
    AND DATE(create_time) = CURDATE()")[0];

    // 统计所有数据
    $all_stats = $cnSql->custom("SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as success,
        SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as failed
    FROM submit_details 
    WHERE user_id = $userInfo[id]")[0];

    $outJson->data = array(
        "today" => $today_stats,
        "all" => $all_stats
    );
    $outJson->msg = "获取成功";
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}

/**
 * 切换任务
 */
if($uri == "/api/user/release/switch"){
    // 获取用户信息
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $userInfo = $cnSql->read_only("users", "token = '$token' and type = 0");
    if(!$userInfo){
        $outJson->msg = "用户不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 获取POST数据
    $postJson = json_decode(file_get_contents('php://input'), true);
    if(!isset($postJson['task_id']) || !isset($postJson['reason'])) {
        $outJson->msg = "参数错误";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    $task_id = $postJson['task_id'];
    $reason = $postJson['reason'];

    // 检查任务是否存在且属于该用户
    $task = $cnSql->read_only("releases", "id = $task_id AND user_id = $userInfo[id] AND status = 1");
    if(!$task) {
        $outJson->msg = "任务不存在或已被处理";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 记录切换原因并重置任务状态
    $cnSql->update_json("releases", array(
        "status" => 5,
        "switch_reason" => $reason,
        "switch_time" => date("Y-m-d H:i:s")
    ), "id = $task_id");

    $outJson->msg = "切换成功";
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}